<template>
  <div class="app-container">
    <!-- <el-button class="marginRB10" type="success" @click="allAgree()" plain
      >批量同意</el-button
    >
    <el-button class="marginRB10" type="warning" @click="allFreeze()" plain
      >批量冻结</el-button
    > -->
    <el-button class="marginRB10" type="primary" @click="getExcel()" plain
      >导出EXCEL</el-button
    >

    <el-date-picker
      class="marginRB10"
      v-model="listQuery.start_at"
      type="datetime"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="选择起始日期"
    ></el-date-picker>
    <el-date-picker
      class="marginRB10"
      v-model="listQuery.end_at"
      type="datetime"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="选择结束日期"
    ></el-date-picker>

    <el-select
      filterable
      v-model="listQuery.status"
      class="filter-item marginRB10"
      placeholder="状态"
      style="width: 200px"
    >
      <el-option
        v-for="item in selectList2"
        :key="item.key"
        :label="item.lab"
        :value="item.key"
      ></el-option>
    </el-select>
    <el-input
      class="marginRB10"
      v-model="listQuery.search"
      placeholder="会长ID|公会ID"
      style="width: 200px"
      clearable
    ></el-input>
    <el-button
      type="primary"
      @click="getList"
      icon="el-icon-search"
      class="marginRB10"
      >搜索</el-button
    >

    <el-table
      ref="dataList"
      :data="menuList"
      style="margin-bottom: 20px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号"> </el-table-column>
      <el-table-column prop="count_time" label="时间">
        <template slot-scope="scope">
          {{ oneWeek(scope.row.count_time * 1000) }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="sociaty_id" label="公会ID"> </el-table-column> -->
      <el-table-column prop="sociaty_no" label="公会ID"> </el-table-column>
      <el-table-column prop="user_code" label="会长ID"> </el-table-column>
      <el-table-column prop="sociaty_name" label="公会名称"> </el-table-column>
      <el-table-column prop="amount" label="成员流水"> </el-table-column>
      <el-table-column prop="rate" label="收益比例（%）"> </el-table-column>
      <el-table-column prop="amount" label="应发金币">
        <template slot-scope="scope">
          {{ fixedTwo((scope.row.amount * scope.row.rate) / 100) }}
        </template>
      </el-table-column>
      <el-table-column prop="reversal" label="冲正">
        <template slot-scope="scope">
          {{ scope.row.reversal ? scope.row.reversal * 1 : 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="real_amount" label="预计实发金币">
        <template slot-scope="scope">
          {{
            fixedTwo(
              (scope.row.amount * scope.row.rate) / 100 +
                (scope.row.reversal ? scope.row.reversal * 1 : 0)
            )
          }}
        </template>
      </el-table-column>
      <el-table-column prop="real_amount" label="实发金币">
        <!-- <template slot-scope="scope">
          {{
            fixedTwo(
              (scope.row.amount * scope.row.rate) / 100 +
                (scope.row.reversal ? scope.row.reversal * 1 : 0)
            )
          }}
        </template> -->
      </el-table-column>
      <el-table-column prop="rebate" label="金额">
        <template slot-scope="scope">
          ￥{{
            fixedTwo(
              (scope.row.amount * scope.row.rate * 0.01 +
                (scope.row.reversal ? scope.row.reversal * 1 : 0)) /
                100
            )
          }}
        </template>
      </el-table-column>
      <el-table-column prop="u_code" label="实发ID"> </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? "待审核" : "" }}
          {{ scope.row.status === 2 ? "已发放" : "" }}
          {{ scope.row.status === 3 ? "已冻结" : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="memo" label="备注"> </el-table-column>
      <el-table-column min-width="300" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 1"
            type="success"
            size="mini"
            @click="handleUpdate1(scope.row)"
            plain
            >同意</el-button
          >
          <el-button
            v-if="scope.row.status === 1"
            type="warning"
            size="mini"
            @click="handleUpdate2(scope.row)"
            plain
            >冻结</el-button
          >
          <el-button
            v-if="scope.row.status === 3"
            type="warning"
            size="mini"
            @click="handleUpdate5(scope.row)"
            plain
            >解冻</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate3(scope.row)"
            plain
            >备注</el-button
          >
          <el-button
            v-if="scope.row.status !== 2"
            type="primary"
            size="mini"
            @click="handleUpdate4(scope.row)"
            plain
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />

    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="时间">
          {{ oneWeek(form.count_time * 1000) }}
        </el-form-item>
        <el-form-item label="公会ID">
          {{ form.sociaty_no }}
        </el-form-item>
        <el-form-item label="公会名称">
          {{ form.sociaty_name }}
        </el-form-item>
        <el-form-item label="房间流水">
          {{ form.amount }}
        </el-form-item>
        <el-form-item label="收益比例（%）" prop="rate">
          <el-input
            v-model="form.rate"
            disabled
            placeholder="请输入收益比例(%)"
          />
        </el-form-item>
        <el-form-item label="应发金币">
          {{ fixedTwo((form.amount * form.rate) / 100) }}
        </el-form-item>
        <el-form-item label="冲正" prop="reversal">
          <el-input-number
            :step="1"
            step-strictly
            v-model="form.reversal"
            placeholder="请输入冲正"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="实发金币">
          {{ fixedTwo((form.amount * form.rate) / 100) }}
        </el-form-item>
        <el-form-item label="实发ID" prop="uid">
          <el-input
            type="number"
            v-model="form.u_code"
            placeholder="请输入实发ID"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      title="编辑备注"
      :visible.sync="dialogFormVisible2"
      @close="handleDialogClose2"
    >
      <el-form
        ref="dataForm2"
        :rules="rules2"
        :model="form2"
        label-position="right"
        label-width="140px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="备注" prop="memo">
          <el-input v-model="form2.memo" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible2 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm2()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveData,
  deleteData,
  updateData,
  listData,
  statisticAgree,
  statisticFreeze,
  statisticUnfreeze,
  statisticExport
} from "@/api/unionWater/userListWater";
export default {
  data() {
    return {
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      selectList2: [
        { key: undefined, lab: "全部分类" },
        { key: "1", lab: "待审核 " },
        { key: "2", lab: "已发放" },
        { key: "3", lab: "已冻结" }
      ],
      menuList: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加"
      },
      form: {
        id: undefined,
        count_time: undefined,
        sociaty_id: undefined,
        sociaty_no: undefined,
        sociaty_name: undefined,
        amount: undefined,
        rate: undefined,
        real_amount: undefined,
        uid: undefined,
        u_code: undefined,
        reversal: 0
      },
      form2: {
        sociaty_id: undefined,
        memo: undefined
      },
      rules: {
        rate: [{ required: true, message: "请输入收益比例", trigger: "blur" }],
        uid: [
          { required: true, message: "请输入实发ID", trigger: "blur" },
          { len: 6, message: "实发ID必须为6个字符", trigger: "blur" }
        ]
      },
      rules2: {
        memo: [{ required: true, message: "请输入备注", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    oneWeek(val) {
      let mondayTime = val - 7 * 24 * 60 * 60 * 1000;
      let sundayTime = val;
      return (
        this.timestampToTime(mondayTime) +
        "~" +
        this.timestampToTime(sundayTime - 24 * 60 * 60 * 1000)
      );
    },
    fixedTwo(i) {
      let num = i.toFixed(3);
      return num.substring(0, num.lastIndexOf(".") + 3);
    },
    loadingFun() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return loading;
    },
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      if (this.listQuery.search) {
        urlData = urlData + `&search=${this.listQuery.search}`;
      }
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`;
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`;
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`;
      }

      listData(urlData).then(response => {
        this.menuList = response.data.list;
        this.total = response.data.meta.total;
        this.listLoading = false;
      });
    },
    handleCreate(row) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    handleUpdate1(row) {
      this.loadingFun();
      let data = { ids: JSON.stringify([row.id]) };
      statisticAgree(data).then(response => {
        this.loadingFun().close();
        if (response.code === 200) {
          this.getList();
          this.submitOk("成功");
        } else {
          this.submitFail("失败");
        }
      });
    },
    handleUpdate2(row) {
      this.loadingFun();
      let data = { ids: JSON.stringify([row.id]) };
      statisticFreeze(data).then(response => {
        this.loadingFun().close();
        if (response.code === 200) {
          this.getList();
          this.submitOk("成功");
        } else {
          this.submitFail("失败");
        }
      });
    },
    handleUpdate5(row) {
      this.loadingFun();
      let data = { id: row.id };
      statisticUnfreeze(data).then(response => {
        this.loadingFun().close();
        if (response.code === 200) {
          this.getList();
          this.submitOk("成功");
        } else {
          this.submitFail("失败");
        }
      });
    },
    handleUpdate3(row) {
      this.form2 = [];
      this.form2.id = row.id;
      this.form2.memo = row.memo;

      this.dialogFormVisible2 = true;

      this.form2 = Object.assign({}, this.form2);
    },
    handleUpdate4(row) {
      this.form = [];
      this.form.id = row.id;
      this.form.count_time = row.count_time;
      this.form.sociaty_id = row.sociaty_id;
      this.form.sociaty_no = row.sociaty_no;

      this.form.sociaty_name = row.sociaty_name;
      this.form.amount = row.amount;
      this.form.rate = row.rate;
      // this.form.real_rate = row.real_rate;
      this.form.real_amount = row.real_amount;
      this.form.uid = row.user_code + "";
      this.form.u_code = row.u_code;
      this.form.reversal = row.reversal * 1;

      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      this.form = Object.assign({}, this.form);
    },
    handleDelete(row) {
      this.loadingFun();
      let data = { ids: row.id };
      deleteData(data).then(response => {
        this.loadingFun().close();
        if (response.code === 200) {
          this.getList();
          this.submitOk("删除成功");
        } else {
          this.submitFail("删除失败");
        }
      });
    },
    getExcel() {
      let urlData = "?type=2";
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`;
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`;
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`;
      }
      if (this.listQuery.search) {
        urlData = urlData + `&search=${this.listQuery.search}`;
      }
      statisticExport(urlData).then(response => {
        location.href = response.data.download_url;
      });
    },
    allAgree() {
      this.loadingFun();
      let delNum = [];
      this.$refs.dataList.selection.forEach(k => {
        delNum.push(k.id);
      });
      if (delNum.length === 0) {
        this.loadingFun().close();
        return;
      }
      let data = { ids: JSON.stringify(delNum) };
      statisticAgree(data).then(response => {
        this.loadingFun().close();
        if (response.code === 200) {
          this.getList();
          this.submitOk("成功");
        } else {
          this.submitFail("失败");
        }
      });
    },
    allFreeze() {
      this.loadingFun();
      // this.$refs.dataList.selection)
      let delNum = [];
      this.$refs.dataList.selection.forEach(k => {
        delNum.push(k.id);
      });
      if (delNum.length === 0) {
        this.loadingFun().close();
        return;
      }
      let data = { ids: JSON.stringify(delNum) };
      statisticFreeze(data).then(response => {
        this.loadingFun().close();
        if (response.code === 200) {
          this.getList();
          this.submitOk("成功");
        } else {
          this.submitFail("失败");
        }
      });
    },
    submitForm() {
      this.loadingFun();

      this.$refs["dataForm"].validate(valid => {
        if (!valid) {
          this.loadingFun().close();
          return;
        }
        let formData = new FormData();
        // for(let item in this.form){this.form[item] === undefined? '':formData.append(item, this.form[item]);}
        formData.append("id", this.form["id"]);
        formData.append("uid", this.form["u_code"]);
        formData.append("rate", this.form["rate"]);
        formData.append(
          "reversal",
          this.form["reversal"] ? this.form["reversal"] : 0
        );

        saveData(formData).then(response => {
          this.loadingFun().close();
          if (response.code === 200) {
            this.getList();
            this.$notify({
              type: "success",
              message: "操作成功",
              position: "bottom-right",
              showClose: false,
              duration: 3000
            });
            this.dialogFormVisible = false;
          } else {
            this.$message({
              message: response.message,
              type: "error"
            });
          }
        });
      });
    },
    submitForm2() {
      this.$refs["dataForm2"].validate(valid => {
        if (!valid) {
          return;
        }
        let formData = new FormData();
        for (let item in this.form2) {
          this.form2[item] === undefined
            ? ""
            : formData.append(item, this.form2[item]);
        }
        updateData(formData).then(response => {
          if (response.code === 200) {
            this.getList();
            this.$notify({
              type: "success",
              message: "操作成功",
              position: "bottom-right",
              showClose: false,
              duration: 3000
            });
            this.dialogFormVisible2 = false;
          } else {
            this.$message({
              message: response.message,
              type: "error"
            });
          }
        });
      });
    },
    resetForm() {
      this.form = {
        id: undefined,
        count_time: undefined,
        sociaty_id: undefined,
        sociaty_no: undefined,
        sociaty_name: undefined,
        amount: undefined,
        rate: undefined,
        real_amount: undefined,
        uid: undefined,
        u_code: undefined
      };
    },
    getDate(data) {
      let date = new Date(data);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    dataTime(val) {
      let oToday = new Date(val);
      let currentDay = oToday.getDay();
      if (currentDay === 0) {
        currentDay = 7;
      }
      let mondayTime =
        oToday.getTime() - (currentDay - 1) * 24 * 60 * 60 * 1000;
      let sundayTime =
        oToday.getTime() + (7 - currentDay) * 24 * 60 * 60 * 1000;
      return (
        this.timestampToTime(mondayTime) +
        "~" +
        this.timestampToTime(sundayTime)
      );
    },
    timestampToTime(timestamp) {
      let date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let strDate = Y + M + D;
      return strDate;
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    },
    handleDialogClose2() {
      if (this.$refs["dataForm2"]) {
        this.$refs["dataForm2"].clearValidate(); // 清除整个表单的校验
      }
    }
  }
};
</script>
